//
//  NewsOfCell.m
//  MY Project For Sport
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "NewsOfCell.h"
#import "CellForHotNews.h"
#import "CellForScroller.h"
#import "NetworkHandle.h"
#import "ModelForHotScroller.h"
#import "ModelForHotNews.h"
#import "CellForFlash.h"
#import "CellForAds.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "CellForImage.h"
#import "CellForRead.h"
#import <MJRefresh.h>
#import <DKNightVersion.h>

#define WEIGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667


@interface NewsOfCell ()<UITableViewDataSource, UITableViewDelegate, NetworkHandleDelegate>


@property (nonatomic, retain) NSMutableArray *arrayForScroller;
@property (nonatomic, retain) NSMutableArray *arrayForHotNews;
@property (nonatomic, copy) NSString *stringForUrl;
@property (nonatomic, assign) NSInteger page;

@end

@implementation NewsOfCell

- (void)dealloc {
    [_tableView release];
    [_arrayForScroller release];
    [_arrayForHotNews release];
    [_stringForUrl release];
    [super dealloc];

}


- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.stringForUrl = @"http://platform.sina.com.cn/sports_client/feed?app_key=2586208540&_version__=3.2.1.01&__os__=android&pid=29&len=20&news_type=0%2C2%2C3%2C101%2C102%2C103%2C106%2C107%2C108%2C118&feed_id=1009&partner=clear&pos=sports&sport_tour=sports&ad=1&pdps_params=%7B%22app%22%3A%7B%22timestamp%22%3A%221453429463084%22%2C%22os%22%3A%22Android%22%2C%22model%22%3A%22ZTE+G717C%22%2C%22device_type%22%3A%224%22%2C%22osv%22%3A%224.2.2%22%2C%22name%22%3A%22cn.com.sina.sports%22%2C%22carrier%22%3A%22%E4%B8%AD%E5%9B%BD%E7%94%B5%E4%BF%A1%22%2C%22device_id%22%3A%22A0000038A97F12%22%2C%22make%22%3A%22ZTE+G717C%22%2C%22channel%22%3A%22%22%2C%22connection_type%22%3A%222%22%2C%22version%22%3A30201001%2C%22ip%22%3A%22fe80%3A%3A4ecb%3Af5ff%3Afe3e%3Ae562%25wlan0%22%7D%7D&client_deviceid=7005145ee5bbe7f1f97c5e227f4ab771";
        
        self.page = 1;
        [self handleHotData];
        [self createTableView];
        [self createFootRefresh];
        [self createHeardRefresh];
  
    }

    return self;

}

/**创建 tableView 并为 cell 赋值*/
- (void)createTableView {

    self.tableView = [[UITableView alloc] initWithFrame:self.contentView.frame style:UITableViewStylePlain];
    [self.contentView addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor grayColor]);
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    //分别注册六中不同的 cell
    
    //普通新闻 cell
    [self.tableView registerClass:[CellForHotNews class] forCellReuseIdentifier:@"poolForNews"];
    // 轮播图 cell
    [self.tableView registerClass:[CellForScroller class] forCellReuseIdentifier:@"poolForScroller"];
    // 视频 cell
    [self.tableView registerClass:[CellForFlash class] forCellReuseIdentifier:@"poolForFlash"];
    // 广告 cell
    [self.tableView registerClass:[CellForAds class] forCellReuseIdentifier:@"poolForAds"];
    // 三个图片的 cell
    [self.tableView registerClass:[CellForImage class] forCellReuseIdentifier:@"poolForImage"];
    // 精读 cell
    [self.tableView registerClass:[CellForRead class] forCellReuseIdentifier:@"poolForRead"];
    
}

/** 第三方引用下拉刷新, 当下拉 tableview 时调用此方法,目的初始化数组, 刷新数据 */
- (void)createHeardRefresh {

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        self.page = 1;
        
         self.stringForUrl = @"http://platform.sina.com.cn/sports_client/feed?app_key=2586208540&_version__=3.2.1.01&__os__=android&pid=29&len=20&news_type=0%2C2%2C3%2C101%2C102%2C103%2C106%2C107%2C108%2C118&feed_id=1009&partner=clear&pos=sports&sport_tour=sports&ad=1&pdps_params=%7B%22app%22%3A%7B%22timestamp%22%3A%221453429463084%22%2C%22os%22%3A%22Android%22%2C%22model%22%3A%22ZTE+G717C%22%2C%22device_type%22%3A%224%22%2C%22osv%22%3A%224.2.2%22%2C%22name%22%3A%22cn.com.sina.sports%22%2C%22carrier%22%3A%22%E4%B8%AD%E5%9B%BD%E7%94%B5%E4%BF%A1%22%2C%22device_id%22%3A%22A0000038A97F12%22%2C%22make%22%3A%22ZTE+G717C%22%2C%22channel%22%3A%22%22%2C%22connection_type%22%3A%222%22%2C%22version%22%3A30201001%2C%22ip%22%3A%22fe80%3A%3A4ecb%3Af5ff%3Afe3e%3Ae562%25wlan0%22%7D%7D&client_deviceid=7005145ee5bbe7f1f97c5e227f4ab771";
        
        self.arrayForHotNews = [NSMutableArray array];
        self.arrayForScroller = [NSMutableArray array];

        
        [self handleHotData];
        
        
    }];

    self.tableView.mj_header = header;

}

/**第三方引用上拉加载, 数据加载完成上拉后调用此方法,目的加载数据 */
-(void)createFootRefresh {
 
    MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        NSString *str = @"http://platform.sina.com.cn/sports_client/feed?app_key=2586208540&_version__=3.2.1.01&__os__=android&pid=29&page=";
        
        NSString *str2 = @"&len=20&news_type=0%2C2%2C3%2C101%2C102%2C103%2C106%2C107%2C108%2C118&feed_id=1009&partner=clear&pos=sports&sport_tour=sports&ad=1&pdps_params=%7B%22app%22%3A%7B%22timestamp%22%3A%221453807862124%22%2C%22os%22%3A%22Android%22%2C%22model%22%3A%22ZTE+G717C%22%2C%22device_type%22%3A%224%22%2C%22osv%22%3A%224.2.2%22%2C%22name%22%3A%22cn.com.sina.sports%22%2C%22carrier%22%3A%22%E4%B8%AD%E5%9B%BD%E7%94%B5%E4%BF%A1%22%2C%22device_id%22%3A%22A0000038A97F12%22%2C%22make%22%3A%22ZTE+G717C%22%2C%22channel%22%3A%22%22%2C%22connection_type%22%3A%222%22%2C%22version%22%3A30201001%2C%22ip%22%3A%22fe80%3A%3A4ecb%3Af5ff%3Afe3e%3Ae562%25wlan0%22%7D%7D&client_deviceid=7005145ee5bbe7f1f97c5e227f4ab771";
        
        
        // 字符串拼接,改变每次上拉加载的链接
        
        self.stringForUrl = [str stringByAppendingFormat:@"%ld%@", ++self.page, str2];
        
        
        [self handleHotData1];
        

    }];
    self.tableView.mj_footer = foot;

}


///** 网络数据解析 */
- (void)handleHotData {
    
    [NetworkHandle handlerJSONWitURL:self.stringForUrl delegate:self];
    
}

/** 下拉加载处理数据 */
- (void)handleHotData1 {
    
    [NetworkHandle handlerJSONWitURL:self.stringForUrl delegate:self];
    
}


/** 数据处理 */
- (void)handleDidComplete:(id)result {
    
    NSDictionary *dic = [result objectForKey:@"result"];
    NSArray *arr = [dic objectForKey:@"data"];
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSDictionary *dict in arr) {
        
        [array addObject:[dict objectForKey:@"data"]];
        
    }
    
    // 如果数组个数为0 加载第一页面的内容, 否则是下拉加载请求的数据
       if (self.arrayForScroller.count == 0) {
        
           self.arrayForScroller = [NSMutableArray array];
           self.arrayForHotNews = [NSMutableArray array];
       
           //此时数组中有两个元素,分别遍历取值, 第一个元素中是存放轮播图的字典
    for (NSDictionary *dicdd in array[0]) {
        
        ModelForHotScroller *model = [[ModelForHotScroller alloc] init];
        
        [model setValuesForKeysWithDictionary:dicdd];
        [self.arrayForScroller addObject:model];
        [model release];
 
        
    }
           // 第二个元素是存放其他新闻的字典
           
    for (NSDictionary *dicddd in array[1]) {

        ModelForHotNews *model2 = [[ModelForHotNews alloc] init];
        [model2 setValuesForKeysWithDictionary:dicddd];
        [self.arrayForHotNews addObject:model2];
        
        NSDictionary *dictt = [dicddd objectForKey:@"img"];
        
        [model2 setValuesForKeysWithDictionary:dictt];
        
        [model2 release];
        
    }
           [self.tableView reloadData];
           // 数据加载完成后结束刷新
           [self.tableView.mj_header endRefreshing];
        
    } else { // 此时是下拉加载请求
    
        
    for (NSDictionary *dic5 in [array lastObject]) {
        
        
        ModelForHotNews *model3 = [[ModelForHotNews alloc] init];
        
        [model3 setValuesForKeysWithDictionary:dic5];
        
        
       [self.arrayForHotNews addObject:model3];
        
        NSDictionary *dictt = [dic5 objectForKey:@"img"];
        
        [model3 setValuesForKeysWithDictionary:dictt];
        
        [model3 release];
    }
    
         [self.tableView reloadData];
        
        // 数据加载完成后停止刷新
        [self.tableView.mj_footer endRefreshing];
    }
    
}

/**返回 cell 的个数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arrayForHotNews.count;
    
}

/**对六中不同的 cell 赋值 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // 轮播图赋值
    if (indexPath.row == 0) {
        
        CellForScroller *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForScroller"];
        
        [cell passModelForHotScroller:self.arrayForScroller];
        
        return cell;
        
    }else {
       
        //其他类型的 cell 赋值
        ModelForHotNews *model = [self.arrayForHotNews objectAtIndex:indexPath.row];
        
        // 普通的新闻 cell 赋值
        if (model.category != nil && model.jktitle != nil) {
            
            CellForHotNews *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForNews"];
            [cell passModelForHotNews:model];
                return cell;
        }else if(model.short_title != nil){  //视频新闻 cell 赋值
        
            CellForFlash *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForFlash"];
            
            [cell passModelForHot:model];
            
            return cell;
        
        } else if (model.categoryid != nil) { //广告 cell 赋值
        
            CellForAds *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForAds"];
            
            [cell passModelForHotNews:model];
            
                return cell;
            
        }else if(model.img_data != nil){ // 三张图片的 cell 赋值
        
            CellForImage *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForImage"];
            
            [cell passModelForHotNews:model];
            
            
            return cell;
        
        }else { // 精读 cell 的赋值
        
            CellForRead *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForRead"];
          
            [cell passModelForHotNews:model];
            return cell;
        }
    
    }
    
}


/**返回不用类型 cell 的高度*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelForHotNews *model = [self.arrayForHotNews objectAtIndex:indexPath.row];
    
    if (indexPath.row == 0) {                                  // 轮播 cell 的高度
        return tableView.frame.size.height / 2.5 ;
        
    } else if (model.category != nil && model.jktitle != nil){ // 普通新闻 cell 的高度
        
        return tableView.frame.size.height / 5.5;
        
    } else if (model.categoryid != nil){ // 广告cell 的高度
        
        return 90 * HEIGHTT;
        
    } else {
        // 精读,视频, cell 的高度
        return tableView.frame.size.height / 4.5;
        
    }
}


- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    
    self.tableView.frame = self.contentView.frame;

}

/**当点击不同的 row 调用此协议方法*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"disappear" object:nil];
    
    if ([self.delegate respondsToSelector:@selector(didClickNewsRow:)]) {
        
        [self.delegate didClickNewsRow:[self.arrayForHotNews objectAtIndex:indexPath.row]];
        
    }
 
    
}


@end
